<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(B卷,100分)- 事件推送（Java & JS & Python & C）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>同一个数轴X上有两个点的集合A&#61;{A1, A2, …, Am}和B&#61;{B1, B2, …, Bn}&#xff0c;Ai和Bj均为正整数&#xff0c;A、B已经按照从小到大排好序&#xff0c;</p> 
<p>A、B均不为空&#xff0c;给定一个距离R(正整数)&#xff0c;列出同时满足如下条件的所有&#xff08;Ai, Bj&#xff09;数对&#xff1a;</p> 
<ol><li>Ai &lt;&#61; Bj</li><li>Ai, Bj之间的距离小于等于R</li><li>在满足1,2的情况下,每个Ai只需输出距离最近的Bj</li><li>输出结果按Ai从小到大的顺序排序</li></ol> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>第一行三个正整数m,n,R</p> 
<p>第二行m个正整数,表示集合A</p> 
<p>第三行n个正整数,表示集合B</p> 
<p></p> 
<p>输入限制&#xff1a;</p> 
<p>1&lt;&#61;R&lt;&#61;100000, 1&lt;&#61;n,m&lt;&#61;100000, 1&lt;&#61;Ai,Bj&lt;&#61;1000000000</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>每组数对输出一行Ai和Bj,以空格隔开</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:64px;">输入</td><td style="width:434px;">4 5 5<br /> 1 5 5 10<br /> 1 3 8 8 20</td></tr><tr><td style="width:64px;">输出</td><td style="width:434px;">1 1<br /> 5 8<br /> 5 8</td></tr><tr><td style="width:64px;">说明</td><td style="width:434px;">无</td></tr></tbody></table> 
<p></p> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>本题数量级非常大&#xff0c;因此使用双重for是肯定会超时的。</p> 
<p></p> 
<p>我的解题思路是利用二分查找。</p> 
<p>关于标准二分查找的实现可以参考Java的Arrays.binarySearch&#xff0c;其他语言实现可以看&#xff1a;</p> 
<p><a href="https://blog.csdn.net/qfc_128220/article/details/130097676?spm&#61;1001.2014.3001.5501" title="算法设计 - 二分法和三分法&#xff0c;洛谷P3382_伏城之外的博客-CSDN博客">算法设计 - 二分法和三分法&#xff0c;洛谷P3382_伏城之外的博客-CSDN博客</a></p> 
<p>中关于binarySearch的具体实现&#xff0c;特别是其中关于有序插入位置的实现原理。</p> 
<p></p> 
<p>本题&#xff0c;我们只需要遍历每一个a[i]&#xff0c;然后通过二分查找去找他们在b中的位置 j &#xff1a;</p> 
<ul><li>如果 j &gt;&#61; 0&#xff0c;则说明b数组中有一个b[j] &#61;&#61; a[i]&#xff0c;此时a[i] b[j]就是符合要求的组合</li><li>如果 j &lt; 0&#xff0c;则说明b数组中没有b[j] &#61;&#61; a[i]&#xff0c;此时 j 其实就是 - insertIdx - 1&#xff0c;其中insertIdx就是a[i]在b中的有序插入位置&#xff0c;因此b[insertIdx] &gt; a[i]&#xff0c;如果 b[insertIdx] - a[i] &lt;&#61; r&#xff0c;那么a[i] b[insertIdx]就是符合要求的组合</li></ul> 
<p></p> 
<p>上面算法的事件复杂度只有O(nlogn)&#xff0c;不会超时。</p> 
<hr /> 
<p>2023.06.15</p> 
<p>找到的有序插入位置可能 insertIdx &#61;&#61; b.length&#xff0c;即使越界位置&#xff0c;此情况b数组中不存在比a[i]大的值</p> 
<hr /> 
<p>2023.07.08</p> 
<p>本题最优策略为同向双指针&#xff0c;可达O(n)时间复杂度</p> 
<p></p> 
<h3>二分查找解法</h3> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Arrays;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    Integer[] tmp &#61;
        Arrays.stream(sc.nextLine().split(&#34; &#34;)).map(Integer::parseInt).toArray(Integer[]::new);

    int m &#61; tmp[0];
    int n &#61; tmp[1];
    int r &#61; tmp[2];

    Integer[] a &#61;
        Arrays.stream(sc.nextLine().split(&#34; &#34;)).map(Integer::parseInt).toArray(Integer[]::new);

    Integer[] b &#61;
        Arrays.stream(sc.nextLine().split(&#34; &#34;)).map(Integer::parseInt).toArray(Integer[]::new);

    getResult(r, a, b);
  }

  public static void getResult(int r, Integer[] a, Integer[] b) {
    for (int ai : a) {
      int j &#61; Arrays.binarySearch(b, ai);

      // 如果在b数组中可以找到ai&#xff0c;则此时j就是ai在b数组中的位置&#xff0c;此时ai和bj是满足要求&#xff0c;且最接近的
      if (j &gt;&#61; 0) {
        System.out.println(ai &#43; &#34; &#34; &#43; b[j]);
      } else {
        // 如果在b数组中找不到ai&#xff0c;则此时j就是ai在b数组中有序插入位置-insertIdx-1&#xff0c;
        // 因此insertIdx &#61; -j-1&#xff0c;此时b[insertIdx]满足大于ai&#xff0c;我们只需要检查b[insertIdx] - ai&lt;&#61;r即可
        int insertIdx &#61; -j - 1;
        // 有序插入位置可能是越界位置
        if (insertIdx &#61;&#61; b.length) continue;
        if (b[insertIdx] - ai &lt;&#61; r) System.out.println(ai &#43; &#34; &#34; &#43; b[insertIdx]);
      }
    }
  }
}
</code></pre> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JS算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const { userInfo } &#61; require(&#34;os&#34;);
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 3) {
    let [m, n, r] &#61; lines[0].split(&#34; &#34;).map((ele) &#61;&gt; parseInt(ele));
    let a &#61; lines[1].split(&#34; &#34;).map(Number);
    let b &#61; lines[2].split(&#34; &#34;).map(Number);
    getResult(a, b, r);
    lines.length &#61; 0;
  }
});

function getResult(a, b, r) {
  for (let ai of a) {
    const j &#61; binarySearch(b, ai);
    if (j &gt;&#61; 0) {
      console.log(&#96;${ai} ${b[j]}&#96;);
    } else {
      const insertIdx &#61; -j - 1;
      if (insertIdx &#61;&#61; b.length) continue;
      if (b[insertIdx] - ai &lt;&#61; r) console.log(&#96;${ai} ${b[insertIdx]}&#96;);
    }
  }
}

function binarySearch(arr, target) {
  let low &#61; 0;
  let high &#61; arr.length - 1;

  while (low &lt;&#61; high) {
    const mid &#61; (low &#43; high) &gt;&gt; 1;
    const midVal &#61; arr[mid];

    if (midVal &gt; target) {
      high &#61; mid - 1;
    } else if (midVal &lt; target) {
      low &#61; mid &#43; 1;
    } else {
      return mid;
    }
  }

  return -low - 1;
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
m, n, r &#61; map(int, input().split())
a &#61; list(map(int, input().split()))
b &#61; list(map(int, input().split()))


def binarySearch(arr, target):
    low &#61; 0
    high &#61; len(arr) - 1

    while low &lt;&#61; high:
        mid &#61; (low &#43; high) &gt;&gt; 1
        midVal &#61; arr[mid]

        if midVal &gt; target:
            high &#61; mid - 1
        elif midVal &lt; target:
            low &#61; mid &#43; 1
        else:
            return mid

    return -low - 1


# 算法入口
def getResult():
    for ai in a:
        j &#61; binarySearch(b, ai)
        if j &gt;&#61; 0:
            print(f&#34;{ai} {b[j]}&#34;)
        else:
            insertIdx &#61; -j - 1
            if insertIdx &#61;&#61; len(b):
                continue
            if b[insertIdx] - ai &lt;&#61; r:
                print(f&#34;{ai} {b[insertIdx]}&#34;)


# 算法调用
getResult()
</code></pre> 
<p></p> 
<h4>C算法源码</h4> 
<pre><code class="language-cpp">#include &lt;stdio.h&gt;

int binarySearch(const int nums[], int nums_size, int key) {
    int low &#61; 0;
    int high &#61; nums_size - 1;

    while(low &lt;&#61; high) {
        int mid &#61; (low &#43; high) &gt;&gt; 1;
        int midVal &#61; nums[mid];

        if(midVal &gt; key) {
            high &#61; mid - 1;
        } else if(midVal &lt; key) {
            low &#61; mid &#43; 1;
        } else {
            return mid;
        }
    }

    return -low - 1;
}

int main() {
    int m, n, r;
    scanf(&#34;%d %d %d&#34;, &amp;m, &amp;n, &amp;r);

    int a[m];
    for(int i&#61;0; i&lt;m; i&#43;&#43;) {
        scanf(&#34;%d&#34;, &amp;a[i]);
    }

    int b[n];
    for(int i&#61;0; i&lt;n; i&#43;&#43;) {
        scanf(&#34;%d&#34;, &amp;b[i]);
    }

    for(int i&#61;0; i&lt;m; i&#43;&#43;) {
        int j &#61; binarySearch(b, n, a[i]);

        if(j &gt;&#61; 0) {
            printf(&#34;%d %d\n&#34;, a[i], b[j]);
        } else {
            int insertIdx &#61; -j - 1;

            if(insertIdx &#61;&#61; n) {
                continue;
            }

            if(b[insertIdx] - a[i] &lt;&#61; r) {
                printf(&#34;%d %d\n&#34;, a[i], b[insertIdx]);
            }
        }
    }

    return 0;
}</code></pre> 
<p></p> 
<h3>同向双指针解法</h3> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Arrays;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    Integer[] tmp &#61;
        Arrays.stream(sc.nextLine().split(&#34; &#34;)).map(Integer::parseInt).toArray(Integer[]::new);

    int m &#61; tmp[0];
    int n &#61; tmp[1];
    int r &#61; tmp[2];

    int[] a &#61; Arrays.stream(sc.nextLine().split(&#34; &#34;)).mapToInt(Integer::parseInt).toArray();

    int[] b &#61; Arrays.stream(sc.nextLine().split(&#34; &#34;)).mapToInt(Integer::parseInt).toArray();

    getResult(r, a, b);
  }

  public static void getResult(int r, int[] a, int[] b) {
    int i &#61; 0;
    int j &#61; 0;

    while (i &lt; a.length &amp;&amp; j &lt; b.length) {
      if (a[i] &lt;&#61; b[j]) {
        if (b[j] - a[i] &lt;&#61; r) System.out.println(a[i] &#43; &#34; &#34; &#43; b[j]);
        i&#43;&#43;;
      } else {
        j&#43;&#43;;
      }
    }
  }
}
</code></pre> 
<h4>JS算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const { userInfo } &#61; require(&#34;os&#34;);
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 3) {
    let [m, n, r] &#61; lines[0].split(&#34; &#34;).map((ele) &#61;&gt; parseInt(ele));
    let a &#61; lines[1].split(&#34; &#34;).map(Number);
    let b &#61; lines[2].split(&#34; &#34;).map(Number);
    getResult(a, b, r);
    lines.length &#61; 0;
  }
});

function getResult(a, b, r) {
  let i &#61; 0;
  let j &#61; 0;

  while (i &lt; a.length &amp;&amp; j &lt; b.length) {
    if (a[i] &lt;&#61; b[j]) {
      if (b[j] - a[i] &lt;&#61; r) console.log(a[i] &#43; &#34; &#34; &#43; b[j]);
      i&#43;&#43;;
    } else {
      j&#43;&#43;;
    }
  }
}
</code></pre> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
m, n, r &#61; map(int, input().split())
a &#61; list(map(int, input().split()))
b &#61; list(map(int, input().split()))


# 算法入口
def getResult():
    i &#61; 0
    j &#61; 0

    while i &lt; len(a) and j &lt; len(b):
        if a[i] &lt;&#61; b[j]:
            if b[j] - a[i] &lt;&#61; r:
                print(f&#34;{a[i]} {b[j]}&#34;)
            i &#43;&#61; 1
        else:
            j &#43;&#61; 1


# 算法调用
getResult()
</code></pre> 
<p> </p> 
<h4>C算法源码</h4> 
<pre><code class="language-cpp">#include &lt;stdio.h&gt;

int main() {
    int m, n, r;
    scanf(&#34;%d %d %d&#34;, &amp;m, &amp;n, &amp;r);

    int a[m];
    for(int i&#61;0; i&lt;m; i&#43;&#43;) {
        scanf(&#34;%d&#34;, &amp;a[i]);
    }

    int b[n];
    for(int i&#61;0; i&lt;n; i&#43;&#43;) {
        scanf(&#34;%d&#34;, &amp;b[i]);
    }

    int i &#61; 0;
    int j &#61; 0;

    while(i &lt; m &amp;&amp; j &lt; n) {
        if(a[i] &lt;&#61; b[j]) {
            if(b[j] - a[i] &lt;&#61; r) {
                printf(&#34;%d %d\n&#34;, a[i], b[j]);
            }
            i&#43;&#43;;
        } else {
            j&#43;&#43;;
        }
    }

    return 0;
}</code></pre> 
<p> </p>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>